import traceback

from rest_framework.permissions import AllowAny

from wass.settings import SECRET_KEY
from apps.notify.serializer import RECEIVE_NOTIFY, PUSH_NOTIFY
from apps.notify.notify_log import logger

from utilities.meta_view import APIView, NotifySuccess
from utilities.custom_exception import EmailSendError
from utilities.errors import NoticeError, TaskNotFoundError, PushNotificationError
from utilities.meta_view import NoticeForcedWaiting
from utilities.utils import get_log_info
from utilities.redis import notify_redis


class Notification(APIView):

    permission_classes = [
        AllowAny,
    ]

    def post(self, *args, **kwargs):
        if self.request.META.get('HTTP_SECRETKEY') != SECRET_KEY:
            return self.permission_denied(self.request)

        request_args = self.request.data

        # no used
        notify_type = request_args.get('notify_type_name')
        func = RECEIVE_NOTIFY.get(notify_type)
        func_push = PUSH_NOTIFY.get(notify_type)
        if not func:
            return NotifySuccess()

        notify_id = request_args.get('notification_id', '')
        # prevent duplicate
        if notify_redis.get(f"notify_id:{notify_id}"):
            return NotifySuccess()

        try:
            func(request_args)
            if func_push:
                func_push(request_args)
            return NotifySuccess(notify_redis, notify_id)
        except PushNotificationError:
            return NotifySuccess(notify_redis, notify_id)
        except EmailSendError as e:
            logger.exception(e)
            return NotifySuccess(notify_redis, notify_id)
        except TaskNotFoundError:
            # logger.info(e)
            return NoticeForcedWaiting()
        except Exception as e:
            logger.exception(e)
            traceback.print_exc()
            raise NoticeError()
        finally:
            logger.info(get_log_info(self.request))
